<template>
  <div class="full-screen-div">
    <HeaderComponent style="position: relative;" @go-back="goBack" :title="title" />
    <div class="content">
      <el-form class="form-container">
        <el-form-item :label="fixedItems[0]" class="form-item">
          <el-input disabled v-model="itemsFixed.empName" class="form-control"></el-input>
        </el-form-item>
        <el-form-item :label="fixedItems[1]" class="form-item">
          <el-input disabled v-model="itemsFixed.empId" class="form-control"></el-input>
        </el-form-item>
        <el-form-item :label="fixedItems[2]" class="form-item">
          <el-input disabled v-model="itemsFixed.deptName" class="form-control"></el-input>
        </el-form-item>
        <el-form-item :label="fixedItems[3]" class="form-item">
          <el-input disabled v-model="itemsFixed.positionName" class="form-control"></el-input>
        </el-form-item>
      </el-form>
      <el-form ref="form" class="form-container">
        <el-form-item v-for="(item, index) in formData" :key="index" :label="item.itemName"
          :prop="'form[' + index + '].value'" class="form-item">
          <template v-if="isDatePicker(item.itemName)">
            <!-- 修改el-date-picker部分 -->
            <el-date-picker @change="(val) => handleDateChange(val, index)" v-model="item.value" type="date"
              placeholder="选择日期时间" class="form-control" value-format="YYYY-MM-DDTHH:mm:ss.SSSZ"></el-date-picker>
          </template>
          <template v-else>
            <el-input :placeholder="item.itemName" v-model="item.value" class="form-control"></el-input>
          </template>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="submitForm" class="submit-button">提交</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRoute } from "vue-router";
import HeaderComponent from "../../component/Header.vue";
import { getProcessDetail } from "../../api/application.js";
import { addApplicationRecord } from "../../api/approval.js";
import { ElMessage } from "element-plus";
import { getSessionStorageObj } from "../../utils/common.js";
import router from "../../router/index.js"; // 确保路径正确
const goBack = () => {
  router.push('/applicationType'); // 返回申请记录列表页
};
//固定项名称，仅作展示
const fixedItems = [
  "申请人姓名",
  "申请人工号",
  "申请人部门名称",
  "申请人职称"
]
const route = useRoute();
const title = ref("");
const formData = ref([]);
const itemsFixed = ref({
  deptName: "",
  empId: "",
  empName: "",
  positionName: "",
});
const params = ref({
  deptId: 0,
  empId: "",
  flowId: 0
});

const id = route.params.id;
const initFormData = async () => {
  title.value = route.params.type;
  const res = await getProcessDetail(id);
  if (res.flag) {
    formData.value = res.result.applicationItems.map((item) => ({
      ...item,
      value: "", // 初始化 value 为空字符串
    }));
  } else {
    console.error("获取流程详情失败:", res.message);
  }
};

onMounted(async () => {
  //初始化好表单
  initFormData();
  //提前装载好相关信息
  let userInfo = getSessionStorageObj("userInfo");
  console.log("userInfo:", userInfo);
  params.value.deptId = userInfo.deptId;
  params.value.empId = userInfo.empId;
  params.value.flowId = id;
  //提前装载好固定项信息
  itemsFixed.value.empId = userInfo.empId;
  itemsFixed.value.empName = userInfo.name;
  itemsFixed.value.deptName = userInfo.deptName;
  itemsFixed.value.positionName = userInfo.positionName;
});

// 修改handleDateChange方法
const handleDateChange = (date, index) => {
  if (!date) return;

  // 将日期转换为UTC时间的00:00:00
  const selectedDate = new Date(date);
  const utcDate = new Date(Date.UTC(
    selectedDate.getFullYear(),
    selectedDate.getMonth(),
    selectedDate.getDate(),
    0, 0, 0
  ));

  // 直接修改formData的值
  formData.value[index].value = utcDate.toISOString();
}

// 移除this.item.value的用法

// 判断是否为日期选择器
const isDatePicker = (itemName) => {
  return itemName.includes("时间") || itemName.includes("time");
};

const submitForm = async () => {
  console.log("提交表单:", formData.value);
  // 表单校验
  const isValid = validateFormData(formData.value);
  if (!isValid) {
    ElMessage({
      message: "请填写所有必填项",
      type: "error",
      duration: 3000,
    });
    return; // 如果校验失败，阻止提交
  }
  // 构建请求参数
  const requestParams = {
    ...params.value,
    items: formData.value.map((item) => ({
      itemId: item.id,
      itemValue: item.value || null, // 确保值为空时发送 null
    })),
    itemsFixed: itemsFixed.value,
  };

  console.log("提交信息:", requestParams);



  try {
    const response = await addApplicationRecord(requestParams);
    if (response.flag) {
      // 请求成功，处理响应数据
      console.log("提交成功");
      ElMessage({
        message: "提交成功",
        type: "success",
        duration: 3000,
      });
      // 重置表单
      initFormData();
      router.push('/applicationRecordsList');
    } else {
      // 请求失败，处理错误
      console.error("提交失败");
      ElMessage({
        message: "提交失败",
        type: "error",
        duration: 3000,
      });
    }
  } catch (error) {
    // 请求过程中发生错误
    console.error("请求错误:", error);
    ElMessage({
      message: "请求发生错误",
      type: "error",
      duration: 3000,
    });
  }
};

// 表单校验函数
const validateFormData = (formData) => {
  for (let one of formData) {
    if (one.value === "" || one.value === null) {
      return false; // 如果有必填项为空，返回 false
    }
  }
  return true; // 所有必填项都已填写，返回 true
};
</script>

<style scoped>
.full-screen-div {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #e1efff;
  display: flex;
  flex-direction: column;
}

.content {
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px;
  height: 80%;
  overflow-y: scroll;
}

.form-container {
  width: 100%;
  max-width: 600px;
}

.el-form-item {
  margin-bottom: 20px;
  /* background-color: red; */
}

.form-item label {
  text-align: left;
  /* 标签左对齐 */
}

.form-control {
  width: 100%;
}

.submit-button {
  width: 90%;
  max-width: 200px;
  /* 限制按钮最大宽度 */
}
</style>